package com.gitee.ywj1352.proxy.dynamic.custom;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Created by wenjie.yang on 3/25/2019.
 */
public class YWJClassLoader extends ClassLoader{
    private File classPathFile;

    public YWJClassLoader(){
        String calssPath = YWJClassLoader.class.getResource("").getPath();
        this.classPathFile = new File(calssPath);
    }

    @Override
    protected Class<?> findClass(String name)throws  ClassNotFoundException{
        String calssName = YWJClassLoader.class.getPackage().getName()+ "."+name;
        if (classPathFile != null){

            File classFile = new File(classPathFile, name.replace("\\.", "/") + ".class");

            if (classFile.exists()){
                FileInputStream in = null;
                ByteOutputStream out  = null;

                try {
                    in = new FileInputStream(classFile);
                    out = new ByteOutputStream();
                    byte[] buff = new byte[1024];
                    int len;
                    while ((len = in.read(buff))!=-1){
                        out.write(buff,0,len);
                    }
                    return defineClass(calssName,out.toByteArray(),0,out.size());
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    out.close();
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }


            }
        }

        return null;
    }




}
